package pers.cj.pdos.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import pers.cj.pdos.entity.Budget;
import pers.cj.pdos.entity.Transfer;
import pers.cj.pdos.mapper.SettAccountMapper;
import pers.cj.pdos.mapper.TransferMapper;
import pers.cj.pdos.service.ITransferService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import pers.cj.pdos.utils.Utils;
import pers.cj.pdos.vo.PacketVo;
import pers.cj.pdos.vo.TransferVo;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenj
 * @since 2019-11-04
 */
@Service
public class TransferServiceImpl extends ServiceImpl<TransferMapper, Transfer> implements ITransferService {
    @Autowired
    TransferMapper transferMapper;
    @Autowired
    SettAccountMapper settAccountMapper;

    @Override
    public List<TransferVo> listVoPage(String companyId, Integer page, Integer limit, Boolean close, String search) {
        return transferMapper.listVo(companyId, Utils.genPage(page,limit),limit,close,search);
    }

    @Override
    public long count(String companyId, Boolean close, String search) {
        return transferMapper.count(companyId,close,search);
    }

    @Override
    public TransferVo getVoById(String id) {
        return transferMapper.getVoById(id);
    }

    @Override
    public boolean checkClose(Transfer transfer) {
        return transferMapper.selectCount(new QueryWrapper<Transfer>().eq("id",transfer.getId()).eq("close",true)) > 0;
    }

    @Override
    public void insert(Transfer transfer) {
        transferMapper.insert(transfer);
        //转入账户+
        settAccountMapper.addBalance(transfer.getAmt(), transfer.getInSettAccountId());
        //转出账户-
        settAccountMapper.addBalance(transfer.getAmt().negate(), transfer.getOutSettAccountId());

    }

    @Override
    public void close(Transfer transfer) {

        Transfer temp = new Transfer();
        temp.setId(transfer.getId());
        temp.setClose(true);
        transferMapper.updateById(temp);

        Transfer db = transferMapper.selectById(transfer.getId());
        //转入账户-
        settAccountMapper.addBalance(db.getAmt().negate(), db.getInSettAccountId());
        //转出账户+
        settAccountMapper.addBalance(db.getAmt(), db.getOutSettAccountId());
    }
}
